import 'package:cached_network_image/cached_network_image.dart';
import 'package:syria_sports/presentation/photo_view_screen/photo_view_screen_screen.dart';
import 'package:syria_sports/presentation/players/player_profile_screen/widgets/profile_loading_widet.dart';
import 'package:syria_sports/widgets/app_bar/outline_icon_button.dart';

import '../../../data/controllers/users_controller.dart';
import '../../../data/models/auth/user.dart';
import '../../../dialogs/active_player_confirmation.dart';
import '../../../dialogs/subscription_dialog.dart';
import '../../../widgets/info_view_widget.dart';
import '../add_player_page/widgets/my_circle_avatar.dart';
import '../../my_qr_code/bloc/my_qr_code_screen.dart';
import '../../user_attendances_list_page/bloc/user_attendances_list_screen.dart';
import '../../subscriptions/user_subscriptions_page/bloc/user_subscriptions_screen.dart';
import 'bloc/player_profile_bloc.dart';
import 'package:flutter/material.dart';
import 'package:syria_sports/core/app_export.dart' hide TextDirection;
import 'package:syria_sports/widgets/app_bar/appbar_subtitle.dart';
import 'package:syria_sports/widgets/app_bar/custom_app_bar.dart';

class PlayerProfileScreen extends StatelessWidget {
  final int index;
  const PlayerProfileScreen({Key? key, required this.index}) : super(key: key);

  static Widget builder({required BuildContext context, User? user ,required int index,}) {
    return BlocProvider<ProfileBloc>(
        create: (context) =>
            ProfileBloc(
                ProfileState(user: user),
            )..add(ProfileInitialEvent(user: user)),
        child: PlayerProfileScreen(index: index,));
  }

  @override
  Widget build(BuildContext context) {
    mediaQueryData = MediaQuery.of(context);
    return BlocBuilder<ProfileBloc, ProfileState>(builder: (context, state) {
      User user = state.user??User.empty();

      return SafeArea(
          child: Scaffold(
              appBar: _buildAppBar(context , user ,BlocProvider.of(context)),
              body: Column(
                children: [
                  if(state.isLoading)
                    const ProfileLoadingWidget()
                  else if(state.isError)
                    Center(child: Text(state.error,style: const TextStyle(color: Colors.white),),)
                  else
                    Expanded(
                    child: SingleChildScrollView(
                      child: Container(
                          width: double.maxFinite,
                          padding: EdgeInsets.symmetric(vertical: 36.v),
                          child: Column(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                Hero(
                                    tag: "player_selected$index",
                                    child:InkWell(
                                        onTap: (){
                                          NavigatorService.push(PhotoViewScreenScreen(image:(user.image==null)?null:CachedNetworkImageProvider(user.image!) ));
                                        },
                                        child:MyCircleAvatar(
                                          width: 65,
                                          imageURL:user.image ,
                                          borderColor: Colors.red,
                                          active: user.activeValue == '1',
                                          activeIconWidth: 32,
                                        ),
                                    ),
                                ),
                                Padding(
                                    padding: EdgeInsets.only(top: 9.v, bottom: 4.v),
                                    child: Column(children: [
                                      Text(user.fullName,
                                          style: theme.textTheme.titleSmall),
                                      SizedBox(height: 8.v),
                                      SelectableText(user.username??"",
                                          style: theme.textTheme.bodySmall)
                                    ])),
                                if(user.barcode != null)
                                Padding(
                                  padding: EdgeInsets.all(2.0.v),
                                  child: IconButton(
                                    iconSize: 64,
                                    icon:  Icon(Icons.qr_code,color: theme.textTheme.titleMedium?.color),
                                    onPressed:(){
                                       Navigator.push(context, MaterialPageRoute(builder: (context) => MyQrCodeScreen(code: user.barcode!,)));
                                    },
                                  ),
                                ),
                                Padding(
                                  padding: const EdgeInsets.all(8.0),
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    children: [
                                      Text('تقييم اللاعب',
                                          style: theme.textTheme.titleLarge),
                                      Padding(
                                        padding: const EdgeInsets.symmetric(horizontal: 32.0),
                                        child: Text('${user.userRate.toStringAsFixed(2)}%',
                                            style: theme.textTheme.titleLarge),
                                      ),

                                    ],
                                  ),
                                ),
                                InfoViewWidget(
                                  value: false,
                                  title: 'تفاصيل التقييم',
                                  children: [
                                    Directionality(
                                      textDirection: TextDirection.ltr,
                                      child: Padding(
                                          padding: EdgeInsets.only(left: 16.h),
                                          child: Row(
                                              mainAxisAlignment: MainAxisAlignment.spaceAround,
                                              crossAxisAlignment: CrossAxisAlignment.center,
                                              children: [
                                                Column(
                                                  children: [
                                                    Row(
                                                      crossAxisAlignment: CrossAxisAlignment.end,
                                                      children: [
                                                        Text(user.commitment??"",
                                                            style: theme.textTheme.titleMedium),
                                                        Text("%".tr,
                                                            style: theme.textTheme.bodySmall),
                                                      ],
                                                    ),
                                                    const SizedBox(height: 4,),
                                                    Text("الالتزام",
                                                        style: theme.textTheme.titleSmall),
                                                  ],
                                                ),
                                                Container(color: Colors.grey,height: 45,width: 1,),
                                                Column(
                                                  children: [
                                                    Row(
                                                      crossAxisAlignment: CrossAxisAlignment.end,
                                                      children: [
                                                        Text(user.agility??"",
                                                            style: theme.textTheme.titleMedium),
                                                        Text("%".tr,
                                                            style: theme.textTheme.bodySmall),
                                                      ],
                                                    ),
                                                    const SizedBox(height: 4,),
                                                    Text("المرونة".tr,
                                                        style: theme.textTheme.titleSmall),
                                                  ],
                                                ),
                                                Container(color: Colors.grey,height: 45,width: 1,),
                                                Column(
                                                  children: [
                                                    Row(
                                                      crossAxisAlignment: CrossAxisAlignment.end,
                                                      children: [
                                                        Text(user.power??"",
                                                            style: theme.textTheme.titleMedium),
                                                        Text("%",
                                                            style: theme.textTheme.bodySmall),
                                                      ],
                                                    ),
                                                    const SizedBox(height: 4,),
                                                    Text("القوة",
                                                        style: theme.textTheme.titleSmall),
                                                  ],
                                                ),

                                              ])),
                                    ),
                                    const Padding(
                                      padding: EdgeInsets.all(32.0),
                                      child: Divider(color: Colors.red),
                                    ),
                                  ],
                                ),

                                Padding(
                                  padding: const EdgeInsets.all(8.0),
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    children: [
                                      Text('مستوى اللاعب',
                                          style: theme.textTheme.titleLarge),
                                      Padding(
                                        padding: const EdgeInsets.symmetric(horizontal: 32.0),
                                        child: Text('level ${user.level??""}',
                                            style: theme.textTheme.titleLarge),
                                      ),

                                    ],
                                  ),
                                ),
                                const Padding(
                                  padding: EdgeInsets.all(8.0),
                                  child: Divider(color: Colors.white54),
                                ),
                                if(PrefUtils.isAdmin())
                                  Column(
                                  children: [
                                    InfoViewWidget(
                                      icon: Icons.contact_mail_outlined,
                                      value: false,
                                      title: 'معلومات التواصل',
                                      children: [
                                        ListTile(
                                          leading: const Icon(Icons.phone, color: Colors.white54),
                                          title: Text("رقم الهاتف:",style: TextStyle(fontSize: 14),),
                                          subtitle: SelectableText(user.phone??"لا يوجد",style: const TextStyle(color: Color(0xffbdbab9)),),
                                          //trailing: Icon(Icons.copy, color: Colors.white54),
                                        ),
                                        /*ListTile(
                                          leading: const Icon(Icons.email, color: Colors.white54),
                                          title: const Text("البريد الالكتروني:",style: TextStyle(fontSize: 14),),
                                          subtitle: SelectableText(user.phone??"لا يوجد",style: const TextStyle(color: Color(0xffbdbab9)),),
                                          //trailing: Icon(Icons.copy, color: Colors.white54),
                                        ),*/
                                      ],
                                    ),
                                    const Padding(
                                      padding: EdgeInsets.all(8.0),
                                      child: Divider(color: Colors.white54),
                                    ),
                                  ],
                                ),

                                Card(
                                  color: Theme.of(context).colorScheme.secondary,
                                  child: ListTile(
                                    onTap: (){
                                      Navigator.push(context, MaterialPageRoute(builder: (context) => UserSubscriptionsScreen(
                                        user:user,
                                      )));
                                    },
                                    leading: Icon(Icons.directions_walk,color:Colors.orange.withOpacity(.6)),
                                    title: Text("التمارين المنتسب لها",style: theme.textTheme.titleSmall),
                                    //subtitle: Text(user.level!,style: CustomTextStyles.bodySmallOnPrimary),
                                    trailing: CustomImageView(
                                      imagePath: ImageConstant.imgArrowLeftBlueGray300,
                                      height: 32.adaptSize,
                                      width: 32.adaptSize,
                                    ),
                                  ),
                                ),
                                Card(
                                  color: Theme.of(context).colorScheme.secondary,
                                  child: ListTile(
                                    onTap: (){
                                      Navigator.push(context, MaterialPageRoute(builder: (context) => UserAttendancesListScreen(
                                        user:user,
                                      )));
                                    },
                                    leading: Icon(Icons.directions_walk,color:Colors.orange.withOpacity(.6)),
                                    title: Text("تسجيلات الحضور",style: theme.textTheme.titleSmall),
                                    //subtitle: Text(user.level!,style: CustomTextStyles.bodySmallOnPrimary),
                                    trailing: CustomImageView(
                                      imagePath: ImageConstant.imgArrowLeftBlueGray300,
                                      height: 32.adaptSize,
                                      width: 32.adaptSize,
                                    ),
                                  ),
                                ),


                              ])),
                    ),
                  ),
                ],
              ),
          ),
      );
    });
  }

  /// Section Widget
  PreferredSizeWidget _buildAppBar(BuildContext context, User user , ProfileBloc cubit) {

    return CustomAppBar(
        leading: OutlineIconButton(
          imagePath: ImageConstant.imgRightIcon,
          onTapped: (){
            Navigator.pop(context);
          },
        ),
      actions: [
        if(PrefUtils.isGymAdmin())
        PopupMenuButton<String>(
          icon: const Icon(Icons.more_vert,color: Colors.orange,),
          color: Theme.of(context).colorScheme.secondary,
          onSelected: (value) {
          if(value == 'add_subscription'){
            showDialog(
              context: context,
              builder: (BuildContext context) {
                return SubscriptionDialog(user: user,);
              },
            );
          }
          if(value == 'reactivate_account') {
            showDialog(
              context: context,
              builder: (BuildContext context) {
                return ActiveConfirmationDialog(
                  playerName: user.fullName,
                  titleUser: 'تفعيل حساب اللاعب',
                  onConfirm: () {
                    UsersController.activateAccount(user.userId??'-1').then((value) {
                      if(value?.state == true) {
                        cubit.add(UpdatePlayerStateEvent(user:user.copyWith(activeValue: '1') ));
                      }
                    });
                  },
                );
              },
            );
          }
          if(value == 'disable_account') {
            showDialog(
              context: context,
              builder: (BuildContext context) {
                return ActiveConfirmationDialog(
                  playerName: user.fullName,
                  titleUser: 'تعطيل حساب اللاعب',
                  onConfirm: () async {
                    await UsersController.disableAccount(user.userId??'-1').then((value) {
                      if(value?.state == true) {
                        cubit.add(UpdatePlayerStateEvent(user:user.copyWith(activeValue: '0') ));
                      }
                    });
                  },
                );
              },
            );
          }
          },
          itemBuilder: (BuildContext context) => [
            PopupMenuItem<String>(
              value: 'add_subscription',
              child: Text('إضافة اشتراك',style: theme.textTheme.titleSmall,),
            ),
            if (user.activeValue == '0')
              PopupMenuItem<String>(
                value: 'reactivate_account',
                child: Text('تفعيل الحساب',style: theme.textTheme.titleSmall,),
              ),
            if (user.activeValue == '1')
              PopupMenuItem<String>(
                value: 'disable_account',
                child: Text('تعطيل الحساب',style: theme.textTheme.titleSmall,),
              ),
          ],
        ),
      ],
        title: AppbarSubtitle(
            text: "ملف اللاعب".tr, margin: EdgeInsets.only(left: 12.h),
        ),
    );
  }

  /// Navigates to the changePasswordScreen when the action is triggered.
  onTapProfileDetailOption(BuildContext context) {

  }
}

